package org.shuma.goods.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.shuma.goods.common.ErrorCode;
import org.shuma.goods.contant.FileConstant;
import org.shuma.goods.domain.DTO.ProductDTO;
import org.shuma.goods.domain.entity.ProductBasicInfo;
import org.shuma.goods.domain.entity.ProductDetailsInfo;
import org.shuma.goods.exception.BusinessException;
import org.shuma.goods.manager.OSSManager;
import org.shuma.goods.mapper.ProductBasicInfoMapper;
import org.shuma.goods.mapper.ProductDetailsInfoMapper;
import org.shuma.goods.mapper.ProductDetailsInfoMapperByXingWang;
import org.shuma.goods.service.ProductDetailsInfoService;
import org.shuma.user.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * (ProductDetailsInfo)表服务实现类
 *
 * @author makejava
 * @since 2024-06-18 13:50:09
 */
@Service("productDetailsInfoService")
public class ProductDetailsInfoServiceImpl implements ProductDetailsInfoService {

    @Resource
    private ProductDetailsInfoMapperByXingWang productDetailsInfoMapperByXingWang;

    final long ONE_M = 10 * 1024 * 1024L;

    @Autowired
    ProductBasicInfoMapper productBasicInfoMapper;

    @Resource
    private ProductDetailsInfoMapper productDetailsInfoMapper;

    @Resource
    private OSSManager ossManager;

    /**
     * 通过ID查询单条数据
     *
     * @param pDetailsId 主键
     * @return 实例对象
     */
    @Override
    public ProductDetailsInfo queryById(Long pDetailsId) {
        return this.productDetailsInfoMapperByXingWang.queryById(pDetailsId);
    }

    /**
     * 分页查询
     *
     * @param productDetailsInfo 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<ProductDetailsInfo> queryByPage(ProductDetailsInfo productDetailsInfo, PageRequest pageRequest) {
        long total = this.productDetailsInfoMapperByXingWang.count(productDetailsInfo);
        return new PageImpl<>(this.productDetailsInfoMapperByXingWang.queryAllByLimit(productDetailsInfo, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param productDTO 实例对象
     * @return 实例对象
     */
    @Override
    public ProductDetailsInfo insert(ProductDTO productDTO,MultipartFile file) {
        ProductDetailsInfo productDetailsInfo = new ProductDetailsInfo();
        BeanUtils.copyProperties(productDTO,productDetailsInfo);
        //调用文件上传
        String fileUrl =uploadByInputStream(file,productDTO.getProductName());
        productDetailsInfo.setProductPicture(fileUrl);
        this.productDetailsInfoMapperByXingWang.insert(productDetailsInfo);
        return productDetailsInfo;
    }

    /**
     * 修改数据
     *
     * @param productDetailsInfo 实例对象
     * @return 实例对象
     */
    @Override
    public ProductDetailsInfo update(ProductDetailsInfo productDetailsInfo) {

        this.productDetailsInfoMapperByXingWang.update(productDetailsInfo);
        return this.queryById(productDetailsInfo.getPDetailsId());
    }

    /**
     * 通过主键删除数据
     *
     * @param pDetailsId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long pDetailsId) {
        return this.productDetailsInfoMapperByXingWang.deleteById(pDetailsId) > 0;
    }


    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
   private String  uploadByInputStream(MultipartFile multipartFile,String productName){
        if (multipartFile == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile);
        // 文件目录：
        String pathPrefix = "shuma";
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + productName + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("%s/%s", pathPrefix, filename);
        try {
            ossManager.putObject(filepath,multipartFile);
            String urlPath = String.format("%s%s", FileConstant.OSS_HOST, filepath);
            // 返回可访问地址
            return urlPath;
        } catch (Exception e) {
            //log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
    }
    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void validFile(MultipartFile multipartFile) {

        if (multipartFile == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());

        if (fileSize > ONE_M) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 5M");
        }
        if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }

    }

    @Override
    public ProductDetailsInfo getProductDetailsInfo(Integer productId, UserVo userVo) {
        Integer userRole = userVo.getUserRole();
        LambdaQueryWrapper<ProductBasicInfo> queryWrapper = new LambdaQueryWrapper<ProductBasicInfo>();

        if(userRole == 0)
            queryWrapper.eq(ProductBasicInfo::getOperator,userVo.getId());
        queryWrapper.eq(ProductBasicInfo::getProductId,productId);

        ProductBasicInfo productBasicInfo = productBasicInfoMapper.selectOne(queryWrapper);
        if(productBasicInfo == null) return null;
        Long id = productBasicInfo.getPDetailsId();

        return productDetailsInfoMapper.selectById(id);
    }




}
